<?php

include_once("pie.php");

require_once("graphs/graph-settings.php");

define("NAVIGATION_ITEM_FILE_BUG", "File a report");
define("NAVIGATION_ITEM_USER_STATS", "User's statistics");
define("NAVIGATION_ITEM_ALL_STATS", "Overall statistics");
define("NAVIGATION_ITEM_USERS", "Users");
define("NAVIGATION_ITEM_LOGIN", "Login");
define("NAVIGATION_ITEM_REGISTR", "Registration");

$userContent['index']['navigation'] = array(
	array('name' => NAVIGATION_ITEM_FILE_BUG, 'link' => 'index.php'),
	array('name' => NAVIGATION_ITEM_USER_STATS, 'link' => 'user.details.php'),
	array('name' => NAVIGATION_ITEM_ALL_STATS, 'link' => 'overall.php'));
	
$userContent['login']['navigation'] = array(
	array('name' => NAVIGATION_ITEM_LOGIN, 'link' => 'login.php'),
//	array('name' => NAVIGATION_ITEM_REGISTR, 'link' => 'registration.php')
	);
	
$adminContent['index']['navigation'] = array(
	array('name' => NAVIGATION_ITEM_USERS, 'link' => 'index.php'),
	array('name' => NAVIGATION_ITEM_ALL_STATS, 'link' => 'overall.php'));

function getNavigation($pageName, $activeItem, $isAdmin) {	
	global $userContent;
	global $adminContent;
	
	$content = $isAdmin ? $adminContent : $userContent;
	
	$pageContent = $content[$pageName];
	$pageContent['active-nav'] = $activeItem;

	return $pageContent;
}

function printNavigationBar($pageName, $activeItem) {

	$isUserLoggedIn = isUserLoggedIn();
	global $loggedInUser;
	$isAdmin = false;
	
	if ($isUserLoggedIn) {
		$isAdmin = $loggedInUser->isAdministrator();		
	}
	
	$navigationBar = '<div id="navigation"><div id="navigationItemsDiv">';
	$pageNavigation = getNavigation($pageName, $activeItem, $isAdmin);

	$navigationBar .= composeNavigationList($pageNavigation);
	$navigationBar .= '</div>';
	
	if($isUserLoggedIn) {		
		$navigationBar .= 
			'<div id="logoutDiv">
				<ul id="navigationList">
					<li><a href="account.php">' . $loggedInUser->username . '</a></li>
					<li><a href="logout.php">Logout</a></li>
				</ul>
			</div>';
	}
	
	$navigationBar .= '</div>';
	echo $navigationBar;
}

function composeNavigationList($navContent) {
	
	$navigationList = '<ul id="navigationList">' . PHP_EOL;
	foreach ($navContent['navigation'] as $i => $value) {
		
		$activeItem = ($value['name'] == $navContent['active-nav']); 

		// compose item
		$navigationList .= '<li>';

		if ($activeItem)  {
			$navigationList .= '<span class="active">';
		}
		
		$navigationList .= '<a href="' . $value['link'] . '">' . $value['name'] . '</a>';
		
		if ($activeItem)  {
			$navigationList .= '</span>';
		}

		$navigationList .= '</li>' . PHP_EOL;		
	}
	
	$navigationList .= '</ul>' . PHP_EOL;
	return $navigationList;
}

function printPostCheckbox($id, $text) {
	$previousValue = getOriginalPost($id);
	$checked = ($previousValue == "on");
	
	printCheckbox($id, $text, $checked);
}

function printCheckbox($id, $text, $checked) {
	
	$checkedString = $checked ? "checked" : "";
	echo '<label for="' . $id . '"><input id="' . $id . '" name="' . $id . '" type="checkbox"' .
			 $checkedString . '>' .	$text . '</label><br>';
}

function printSelect($selectId, $onChangeJsMethod, $changedElementInfo,
		$optionElements, $defaultOptionValue, $class) {

	$jsString = ($onChangeJsMethod == null) ? "" :
		'" onchange=\'' . $onChangeJsMethod . '(' . $changedElementInfo . ', this.options[this.selectedIndex].value)\'';
		
	echo '<select class="' . $class . '" id="' . $selectId . '" name="' . $selectId . '"'
		. $jsString . ' onkeyup="this.blur();this.focus();">';

	foreach ($optionElements as $i => $element) {
		$selectedString = ($defaultOptionValue == $element['value']) ? ' selected="selected"' : "";
		
		echo '<option value=\'' . $element['value'] . '\'' . $selectedString . '>' . $element['description'] . '</option>';
	}
	
	echo '</select>';
}

function printRadio($id, $class, $name, $value, $checked) {
	$checkedString = $checked ? "checked" : "";
	
	echo '<input class="' . $class . '" type="radio" id="' . $id . '" name="' . $name . '" value="' . $value . '" ' . $checkedString . '>';
}

function printPageHead($onLoadJsCommand, $headerGeneratorFunc) {
	?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
		<head>
			<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
			<title><?php global $websiteName; echo $websiteName; ?></title>
			<link rel="stylesheet" href="css/960.css" type="text/css" media="screen" charset="utf-8" />
			<link rel="stylesheet" href="css/template.css" type="text/css" media="screen" charset="utf-8" />
			<link rel="stylesheet" href="css/colour.css" type="text/css" media="screen" charset="utf-8" />
			<script type="text/javascript" src="js/jquery-1.7.js"></script>
			<script type="text/javascript" src="js/popup.js"></script>
		
			<?php if (is_string($onLoadJsCommand)) { call_user_func($headerGeneratorFunc); } ?>			
		</head>
		<body onload=<?php if (is_string($onLoadJsCommand)) { echo '"' . $onLoadJsCommand . '"'; }?>>
		<h1 id="head"><?php global $websiteName; echo $websiteName; ?></h1>
	<?php 	
}

function getOriginalPost($key) {
	if (!isset($_POST[$key])) {
		return null;
	}
	
	return htmlspecialchars($_POST[$key]);
}

function readPost($index) {
	if (!isset($_POST[$index])) {
		return null;
	}
	
	return trim($_POST[$index]);
}

function readGet($index) {
	if (!isset($_GET[$index])) {
		return null;
	}
	
	return trim($_GET[$index]);
}

function convertDbTimeToString($time) {
	$minutes = $time % 60;
	$hours = floor($time / 60);
	
	return $hours . "h " . $minutes . "m";
}

function parseDebuggingTime($text) {
	$result['error'] = "";
	
	if ((!isset($text)) || ($text == "")) {
		$result['error'] = "Please fill in the debugging time";
		return $result;
	}

	if (preg_match('"^([0-9]+)h$"', $text, $regexpResult)) {
		$result['time'] = $regexpResult[1] * 60;
		return $result;
	}

	if (preg_match('"^([0-9]+)m$"', $text, $regexpResult)) {
		$result['time'] = $regexpResult[1];
		return $result;
	}
	
	if (preg_match('"^([0-9]+)h ([0-9]+)m$"', $text, $regexpResult)) {
		$result['time'] = ($regexpResult[1] * 60) + $regexpResult[2];		
		return $result;
	}
	
	$result['error'] = "The time '" . htmlspecialchars($text) . "' could not be parsed";
	return $result;
}

function printUserList($users) {
?>
	<table>
		<thead>
			<tr>
				<th>User name</th>
				<th>Email</th>
				<th>Development time</th>
				<th>Debugging time</th>
				<th>Submitted reports</th>
				<th>Actions</th>
			</tr>
		</thead>
		<tbody>
		
		<?php 
			foreach ($users as $i => $user) {
				echo '<tr>';
				
				echo "<td>$user->username</td>";
				echo "<td>$user->email</td>";
				echo "<td>" . convertDbTimeToString($user->develTime) . "</td>";
				echo "<td>" . convertDbTimeToString($user->debuggingTime) . "</td>";
				echo "<td>$user->reportsCount</td>";
				echo "<td><a href=\"user.details.admin.php?userid=$user->userId\">Details</a></td>";
				
				echo '</tr>';
			}			
		?>
		</tbody>
	</table>
<?php 	
}

function printOverallStats($reportsCount, $averageDevelopmentTime, $averageDebuggingTime, $userId) {
?>
	<table>
		<tbody>
			<tr>
				<td>Reported bugs:</td>
				<td>
					<?php 
						echo "$reportsCount";
					?></td>
			</tr>
			<tr>
				<td>Average development time</td>
				<td>
					<?php 
						echo "$averageDevelopmentTime hours";
					?></td>
			</tr>
			<tr>
				<td>Average debugging time</td>
				<td><?php
					echo "$averageDebuggingTime hours";
				
					if ($averageDevelopmentTime < $averageDebuggingTime) {
						
					} else if ($averageDevelopmentTime != 0) {
						$ratio = round($averageDebuggingTime / $averageDevelopmentTime, 3) * 100;
						echo " ($ratio% of the development time)";
					}
				
				 	?>
				 </td>
			</tr>

			<tr>
				<td></td>
				<td></td>
			</tr>

			<tr>
				<td><a href="graphs/tools.usage.graphs.php?userId=<?php echo $userId; ?>">Link for usages of debugging tools</a></td>
				<td></td>
			</tr>
		</tbody>
	</table>
<?php 
}

function printUserDetails($user, $supervised) {
?>
	<table>
		<tbody>
			<tr>
				<td>Total development time</td>
				<td>
					<?php 
						echo round($user->develTime / 60, 1) . " hours";
						
						if (!$supervised) {
							echo '<a href="user.data.php">Update here</a>';
						}
						
					?></td>
			</tr>
			<tr>
				<td>Total debugging time</td>
				<td><?php
					echo round($user->debuggingTime / 60, 1) . " hours";
				
					if ($user->develTime < $user->debuggingTime) {
						if (!$supervised) {
							echo " (Debugging time larger than development time, please update it)";
						}
						
					} else if ($user->develTime != 0) {
						$ratio = round($user->debuggingTime / $user->develTime, 3) * 100;
						echo " ($ratio% of the development time)";
					}
				
				 	?>
				 </td>
			</tr>
			<tr>
				<td><a href="user.reports.overview.php?userId=<?php echo $user->userId; ?>">Reported bugs...</a></td>
			</tr>
			
		</tbody>
	</table>

<?php 	
}

function printReports($reportStats) {
?>
	<table>
		<tbody>
			<tr>
				<th>ID</th>
				<th>Reported time</th>
				<th>Debugging time</th>
				<th>Root cause</th>
				<th>Review pending</th>
				<th>Actions</th>
			</tr>

		<?php 
		
			$rowCount = 0;
			$rootCauses = getRootCauses();

			foreach ($reportStats->reports as $i => $report) {
				//$rowClassname = ($rowCount % 2 == 0) ? "usageTableOddRow" : "";
				$rowClassname = ""; // TODO: improve style
				
				echo '<tr class="' . $rowClassname . '">';

				$rootCauseName = "Unspecified";
				if ($report->rootCause != "") {
					$rootCause = findDbItem($rootCauses, "rootCauseId", $report->rootCause);
					$rootCauseName = ($rootCause != null) ? $rootCause->name :
						"Error, root cause with id " . $report->rootCause . " does not exists!";  					
				}
				
				$requestPending = ($report->reviewReason != "") && ($report->reviewed == 0); 
				$requestPending = $requestPending ? "Yes" : "No"; 
				
				echo "<td>$report->reportId</td>";
				echo "<td>$report->reportTime</td>";
				echo "<td>" . convertDbTimeToString($report->debuggingTime) . "</td>";
				echo "<td>$rootCauseName</td>";
				echo "<td>$requestPending</td>";
				echo '<td><a href="report.details.php?reportId=' . $report->reportId . '">Details</a></td>';
				
				echo "</tr>";
				
				$rowCount++;
			}
			
		?>
		</tbody>
	</table>

<?php 	
}

function createCategoriedItemName($itemName, CategoryInfo $catInfo) {
	
	if ($catInfo->singleCategoryForAll) {
		return "$itemName [$catInfo->subcategoryName]";
	}
	
	return "$itemName [$catInfo->categoryName" . " / " . "$catInfo->subcategoryName]";
}

function printReportDetails(ReportStats $report) {
	$userStats = new UserStats($report->userId);
	$userStats->loadStats();
	
	$complexities = getDebuggingComplexities();
	$debuggingComplexity = findDbItem($complexities, "complexityId", $report->complexity);
	
	$feelings = getFeelings();
	$feeling = findDbItem($feelings, "feelingId", $report->feelings);
	
	$detections = getDetections();
	$detection = findDbItem($detections, "detectionId", $report->detectionWay);
	
	$detectionCatInfo = getDbDoubleCategoryInfo($detection->subcategoryId, "detection_Way_Subcategories", "detection_Way_Categories");
	$detectionString = createCategoriedItemName($detection->name, $detectionCatInfo); 
	
	$detectionFlags = getReportFlags($report->reportId, "detection_Flags");
	$detectionFlags = $detectionFlags['flags'];		// TODO: better error handling
	
	$rootCauses = getRootCauses();
	$rootCause = findDbItem($rootCauses, "rootCauseId", $report->rootCause);

	$rootCauseCatInfo = getDbDoubleCategoryInfo($rootCause->subcategoryId, "root_Cause_Subcategories", "root_Cause_Categories");
	$rootCauseString = createCategoriedItemName($rootCause->name, $rootCauseCatInfo);
	
	$rootCauseFlags = getReportFlags($report->reportId, "root_Cause_Flags");
	$rootCauseFlags = $rootCauseFlags['flags'];
	
	$methodUsages = getReportUsages($report->reportId, "debugging_Method_Usages", "debugging_Methods", "Debugging_Method");
	$toolUsages = getReportUsages($report->reportId, "debugging_Tool_Usages", "debugging_Tools", "Debugging_Tool");
?>
	<div class="grid_16">
		<div class="box">
			<h2>Report <?php echo $report->reportId; ?> details</h2>
			<table>
				<tbody>
					<tr>
						<td>Reporter:</td>
						<td><?php echo $userStats->username; ?></td>
					</tr>
					<tr>
						<td>Report time:</td>
						<td><?php 
							$datetime = strtotime($report->reportTime);
							$dateString = date("j.n. Y, H:i:s", $datetime);
						
							echo $dateString;
							?>
						</td>
					</tr>
					<tr>
						<td>Debugging time:</td>
						<td><?php echo convertDbTimeToString($report->debuggingTime); ?></td>
					</tr>
					<tr>
						<td>Complexity:</td>
						<td><?php echo $debuggingComplexity->description; ?></td>
					</tr>
					<tr class="reportDetailDelimiterRow">
						<td>Feelings:</td>
						<td><?php echo $feeling->description; ?></td>
					</tr>
				<?php
				
					if ($report->reviewReason != "") {
				?>
					<tr>
						<td>Reviewed:</td>
						<td><?php echo ($report->reviewed) ? "Yes" : "No"; ?></td>
					</tr>
					<tr class="reportDetailDelimiterRow">
						<td>Reason for reviewing:</td>
						<td><?php echo htmlspecialchars($report->reviewReason); ?></td>
					</tr>
					
				<?php 
					}
				?>
					<tr>
						<td>Revision:</td>
						<td><?php echo $report->revisionId; ?></td>
					</tr>
					<tr class="reportDetailDelimiterRow">
						<td>Comment:</td>
						<td><?php echo htmlspecialchars($report->comment); ?></td>
					</tr>
					<tr>
						<td><b>Detection:</b></td>
						<td><?php echo $detectionString; ?></td>
					</tr>
					<tr class="reportDetailDelimiterRow">
						<td>Detection flags:</td>
						<td>
						<?php 
							foreach($detectionFlags as $i => $flag) {
								if ($flag->value == "1") {
									echo $flag->description . "<br>";
								}
							}
						?>
						</td>
					</tr>
					<tr>
						<td><b>Root cause:</b></td>
						<td><?php echo $rootCauseString; ?></td>
					</tr>
					<tr class="reportDetailDelimiterRow">
						<td>Root cause flags:</td>
						<td>
						<?php 
							foreach($rootCauseFlags as $i => $flag) {
								if ($flag->value == "1") {
									echo $flag->description . "<br>";
								}
						}
						?>
						</td>
					</tr>

				</tbody>
			</table>

			<br></br>

			<table>
				<tbody>
					<tr class="reportDetailHeaderRow">
						<td>Used methods</td>
						<td>Usefulness</td>
					</tr>
				<?php
					$usagesCount = count($methodUsages);
				
					foreach ($methodUsages as $i => $usage) {
						if ($i == ($usagesCount -1 )) {
							echo '<tr class="reportDetailDelimiterRow">';
						} else {
							echo "<tr>";
						}
						
						$usageCatInfo = getDbSingleCategoryInfo($usage->categoryId, "debugging_Method_Categories");
						$usageDescription = createCategoriedItemName($usage->describedEntity, $usageCatInfo);
						
						echo "<td>$usageDescription</td>";
						echo "<td>$usage->usefulness</td>";
						echo "</tr>";
					}
				?>
					<tr class="reportDetailHeaderRow">
						<td>Used tools</td>
						<td>Usefulness</td>
					</tr>
				<?php
					foreach ($toolUsages as $i => $usage) {

						$toolCatInfo = getDbSingleCategoryInfo($usage->categoryId, "debugging_Tool_Categories");
						$usageDescription = createCategoriedItemName($usage->describedEntity, $toolCatInfo);
						
						echo "<tr>";
						echo "<td>$usageDescription</td>";
						echo "<td>$usage->usefulness</td>";
						echo "</tr>";
					}
				?>
				</tbody>
			</table>
		</div>
	</div>
<?php 
}

function printPageFoot() {
	?>
	
					<div id="foot">
					<i>Designed by </i><a href="http://mathew-davies.co.uk/">Mathew Davies</a>
				</div>
			
		</body>
	</html>
	<?php 
}

function printSingleUserGraphs($userId) {
	$piesSrcs = array("pie.detection.php", "pie.root.causes.php", "pie.root.causes.time.php");
	
	foreach ($piesSrcs as $i => $src) {
		$link = $src . "?userId=" . $userId;
			
		echo '<img src="' . $link . '" width="' . GRAPH_WIDTH . '" height="' . GRAPH_HEIGHT . '"></img>';
	}
}

?>